// 2025/10/20
// 求根节点到叶节点数字之和

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int ans = 0;

    void dfs(TreeNode* root, int prev)
    {
        prev = prev * 10 + root->val;
        if(!root->left && !root->right)
        {
            ans += prev;
            return;
        }
        if(root->left)
        {
            dfs(root->left, prev);   
        }
        if(root->right)
        {
            dfs(root->right, prev);
        }
    }

    int sumNumbers(TreeNode* root) {
        if(root == nullptr)
            return 0;

        dfs(root, 0);
        return ans;    
    }
};